package com.chindeo.h5.x5.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.pm.ApplicationInfo;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.chindeo.h5.x5.IWebChromeClient;
import com.chindeo.h5.x5.IWebViewClient;
import com.tencent.smtt.sdk.CookieManager;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;

public class X5WebView extends WebView {

    public X5WebView(@NonNull Context context) {
        super(context);
        init(context);
    }

    @SuppressLint("SetJavaScriptEnabled")
    public X5WebView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
        Settings.nocacheSetting(this);
        this.getView().setClickable(true);
    }

    void init(@NonNull Context context) {
        isDebug(context);
        setWebViewClient(new IWebViewClient());
        defaultChromeClient();
        //
        try {
            Activity activity = getActivity(context);
            if (activity != null) {
                Window window = activity.getWindow();
                if (window != null) {
                    window.setFormat(PixelFormat.TRANSLUCENT);
                    if (Integer.parseInt(Build.VERSION.SDK) >= 11) {
                        window.setFlags(
                                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED
                        );
                    }
                    window.getDecorView().addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
                        ArrayList<View> outView = new ArrayList<>();
                        window.getDecorView().findViewsWithText(outView, "QQ浏览器", View.FIND_VIEWS_WITH_TEXT);
                        if (outView.size() > 0) {
                            outView.get(0).setVisibility(View.GONE);
                        }
                    });
                    window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public final void setWebChromeClient(WebChromeClient webChromeClient) {
        if (getWebChromeClient() != null && getWebChromeClient() instanceof IWebChromeClient) {
            IWebChromeClient orgClient = (IWebChromeClient) getWebChromeClient(), newClient = (IWebChromeClient) webChromeClient;
        }
        super.setWebChromeClient(webChromeClient);
    }

    public final X5WebView defaultChromeClient() {
        setWebChromeClient(new IWebChromeClient());
        return this;
    }

    @Override
    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        boolean ret = super.drawChild(canvas, child, drawingTime);
        if (isDebug()) {// 调试模式下显示相关信息
            setBackgroundColor(85621);
            canvas.save();
            Paint paint = new Paint();
            paint.setColor(0x7fff0000);
            paint.setTextSize(24.f);
            paint.setAntiAlias(true);
            if (getX5WebViewExtension() != null) {
                canvas.drawText(this.getContext().getPackageName() + "-pid:"
                        + android.os.Process.myPid(), 10, 50, paint);
                canvas.drawText(
                        "X5  Core:" + QbSdk.getTbsVersion(this.getContext()), 10,
                        100, paint);
            }
            else {
                canvas.drawText(this.getContext().getPackageName() + "-pid:"
                        + android.os.Process.myPid(), 10, 50, paint);
                canvas.drawText("Sys Core", 10, 100, paint);
            }
            canvas.drawText(Build.MANUFACTURER, 10, 150, paint);
            canvas.drawText(Build.MODEL, 10, 200, paint);
            canvas.restore();
        }
        return ret;
    }
    public interface Settings {

        static void clearCookie(Context context) {
            if (context == null) return;
            CookieSyncManager.createInstance(context.getApplicationContext());
            CookieManager.getInstance().removeAllCookie();
        }

        @SuppressLint("SetJavaScriptEnabled")
        static void commonSettings(X5WebView x5) {
            x5.setWebViewClient(new IWebViewClient());
            WebSettings webSetting = x5.getSettings();
            defaultSettings(webSetting);
            webSetting.setAppCachePath(x5.getContext().getDir("appcache", 0).getPath());
            webSetting.setDatabasePath(x5.getContext().getDir("databases", 0).getPath());
            webSetting.setGeolocationDatabasePath(x5.getContext().getDir("geolocation", 0)
                    .getPath());
            // webSetting.setPreFectch(true);
            CookieSyncManager.createInstance(x5.getContext().getApplicationContext());
            CookieSyncManager.getInstance().sync();
        }

        static void nocacheSetting(X5WebView x5) {
            WebSettings webSetting = x5.getSettings();
            webSetting.setJavaScriptCanOpenWindowsAutomatically(true);//设置js可以直接打开窗口，如window.open()，默认为false
            defaultSettings(webSetting);
            webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
            // this.getSettingsExtension().setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);//extension
            // settings 的设计
        }

        static void openFileChooseSettings(X5WebView x5) {
            WebSettings webSetting = x5.getSettings();
            defaultSettings(webSetting);
            webSetting.setDefaultTextEncodingName("UTF-8");
            webSetting.setAllowContentAccess(true); // 是否可访问Content Provider的资源，默认值 true
            // 是否允许通过file url加载的Javascript读取本地文件，默认值 false
            webSetting.setAllowFileAccessFromFileURLs(false);
            // 是否允许通过file url加载的Javascript读取全部资源(包括文件,http,https)，默认值 false
            webSetting.setAllowUniversalAccessFromFileURLs(false);
        }

        @SuppressLint("SetJavaScriptEnabled")
        static void defaultSettings(WebSettings webSetting) {
            webSetting.setLoadsImagesAutomatically(true); // 加载图片
            webSetting.setJavaScriptEnabled(true);//是否允许JavaScript脚本运行，默认为false
            webSetting.setAllowFileAccess(true);
            webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
            webSetting.setSupportZoom(true);//是否可以缩放，默认true
            webSetting.setBuiltInZoomControls(true);//是否显示缩放按钮，默认false
            webSetting.setUseWideViewPort(true);//设置此属性，可任意比例缩放。大视图模式
            webSetting.setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
            webSetting.setSupportMultipleWindows(true);
            // webSetting.setLoadWithOverviewMode(true);
            webSetting.setAppCacheEnabled(true);//是否使用缓存
            // webSetting.setDatabaseEnabled(true);
            webSetting.setDomStorageEnabled(true);//开启本地DOM存储
            webSetting.setGeolocationEnabled(true);
            webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
            // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
            webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
            // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
            // 特别注意：5.1以上默认禁止了https和http混用，以下方式是开启
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                // android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW = 0
                webSetting.setMixedContentMode(0);
            }
        }
    }

    public static Type getGenericSuperType(Type type) {
        if (type instanceof ParameterizedType) {
            Type[] actualTypes = ((ParameterizedType) type).getActualTypeArguments();
            if (actualTypes.length > 0) {
                Type actualType = actualTypes[0];
                if (actualType instanceof ParameterizedType) {
                    return actualType;
                }
            }
        }
        return null;
    }

    @Nullable
    public static Activity getActivity(Context context) {
        if (context instanceof Activity) {
            return (Activity) context;
        }
        if (context instanceof ContextWrapper) {
            return getActivity(((ContextWrapper) context).getBaseContext());
        }
        return null;
    }

    @Nullable
    public static FragmentActivity getFragmentActivity(Context context) {
        if (context instanceof FragmentActivity) {
            return (FragmentActivity) context;
        }
        if (context instanceof ContextWrapper) {
            return getFragmentActivity(((ContextWrapper) context).getBaseContext());
        }
        return null;
    }

    private static Boolean DEBUG = null;

    public static void setDebug(boolean debug) {
        DEBUG = debug;
    }

    public static boolean isDebug() {
        return DEBUG != null && DEBUG;
    }

    protected static void isDebug(Context context) {
        if (DEBUG == null) {
            DEBUG = context.getApplicationInfo() != null &&
                    (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        }
    }

}
